import React, {Component} from 'react';
import {StyleSheet, Image, View} from 'react-native';
import {Carousel} from '@ant-design/react-native';
import {getAdvertList} from '~/api/advert';

class BannerView extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dot_index: 1,
            img_list: [],
        };
        this.setBanner();
    }

    //设置轮播广告图
    setBanner = () => {
        getAdvertList({
            condidate: {state: 1, m_type: 5, kind: 1, type: 1},
        }).then((r) => {
            if (r.code === 0) {
                this.setState({
                    img_list: r.data,
                });
            }
        });
    };

    setDot = (index) => {
        this.banner.goTo(index);
    };

    render() {
        return (
            <View style={styles.bannerView}>
                <View style={styles.bannerBox}>
                    {this.state.img_list.length > 0 && (
                        <Carousel style={styles.bannerList} afterChange={this.setDot} dots={false} autoplayInterval={5000} autoplay infinite>
                            {this.state.img_list.map((item, index) => (
                                <Image key={index} style={styles.bannerImage} source={{uri: item.img_url}} />
                            ))}
                        </Carousel>
                    )}
                </View>
                {this.state.img_list.length > 0 && (
                    <Carousel
                        style={styles.pagination}
                        dotStyle={styles.defaultLine}
                        dotActiveStyle={styles.activeLine}
                        ref={(ref) => {
                            this.banner = ref;
                        }}>
                        {this.state.img_list.map((item, index) => (
                            <View key={index} />
                        ))}
                    </Carousel>
                )}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    bannerView: {
        width: '100%',
        aspectRatio: 1 / 0.52,
    },
    bannerBox: {
        borderRadius: 8,
        overflow: 'hidden',
        backgroundColor: 'lightgray',
    },
    bannerList: {
        width: '100%',
        aspectRatio: 1 / 0.48,
    },
    bannerImage: {
        width: '100%',
        height: '100%',
    },
    pagination: {
        height: 15,
    },
    defaultLine: {
        width: 10,
        height: 1,
        marginBottom: -5,
        backgroundColor: '#aaa',
    },
    activeLine: {
        backgroundColor: '#000',
    },
});

export default BannerView;
